#include "head_cli.h"
/**
 *	get_cmd - 下载文件命令功能函数
 *	
 *  @addr: 连接到服务器端的socket地址
 *
 *  @cmd: 执行的命令字符串  	   "get filename\n"
 *
 *
 */


void get_cmd(struct sockaddr_in client, char *Cmd)
{	
	int sockfd;
	int ret;//错误判断
	char buffer[N];//判断文件存不存在
	char filename[N];//存放文件名
	int size;//大小
	int fd;//比例
	int  nbytes;
	
	//1.开机
	sockfd = socket(AF_INET, SOCK_STREAM, 0);
	if (sockfd < 0) {
		perror("socket");
		exit(1);
	}
	//拨号
	ret = connect(sockfd, (struct sockaddr *)&client, sizeof(client));
	if (ret < 0) {
		printf("connect 连接失败\n");
		exit(1);
	}
	//发送数据 Cmd  
	ret = write(sockfd, Cmd, N);//发送get filename\n命令给服务器端
	if (ret < 0) {
		perror("write");
		exit(1);
	}
	//怎么判断文件存不存在？  open函数 打开失败返回 -1；
	bzero(buffer, N);  //read 等待客户端的判断
	ret = read(sockfd, buffer,N);
	if(ret < 0){
		perror("read at get filename");
		printf("文件存在\n");
		exit(1);
	}
	
	if (!strncmp(buffer, "error", 5)) { //服务器端不存在下载的文件
		printf("server not exists %s file\n", Cmd+4);
		return ;
	} else {
		//要下载的文件大小
		size = atoi(buffer);
		printf("recv file len = %d start ...\n", size);
	}
	//提取文件名
	bzero(filename, N);
	strncpy(filename, Cmd+4, strlen(Cmd)-4);
	printf("filename=%s\n", filename);
	//打开文件 filename
	//分别代表只写、创建文件和截断文件的权限。
	//O_TRUNC：如果文件已经存在，将其截断为0长度。（不理解）
	fd = open(filename, O_WRONLY|O_CREAT|O_TRUNC, 0644);
	if (fd < 0) {
		perror("open");
		exit(1);
	}

	char buf[N];
	int ft = 0;//下载百分比
	int count = 0;
	while (1) {
		bzero(buf, N);
		nbytes = read(sockfd, buf, N);//读取返回值
		if (nbytes < 0) {
			perror("read");
			return ;
		}
			
		if(nbytes == 0) //下载完成终止循环
			break;
		
		ret = write(fd, buf, nbytes);
		if (ret < 0) {
			perror("write at get_cmd");
			return;			
		}
		printf("write nbytes %d to file\n", ret);
		count += nbytes;
		ft = count*100/size;
		system("clear");
		//printf(PURPLE"\n\n\t\t**************** 下载 ******************\n");
		printf("\t\t************ get %s  %d%% **********\n",filename,ft);
		//printf("\t\t****************************************\n"NONE);
		usleep(1000);
	}
	//printf(PURPLE"\n\n\t\t**************** 下载 ******************\n");
	printf("\t\t************ get %s  %d%% **********\n",filename,ft);
	//printf("\t\t****************************************\n"NONE);
	
	close(fd);
	close(sockfd);
	printf("下载文件到客户端\n");
	printf("execute download ...count=%d size=%d \n", count, size);
	
}


